package booksystem.controller;

import booksystem.dao.BookDao;
import booksystem.dao.CartDao;
import booksystem.dao.OrderDao;
import booksystem.dao.impl.BookDaoImpl;
import booksystem.dao.impl.CartDaoImpl;
import booksystem.dao.impl.OrderDaoImpl;
import booksystem.entity.Book;
import booksystem.entity.Order;
import booksystem.utils.GetOrderIDUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@WebServlet(name = "OrderServlet", urlPatterns = "/order")
public class OrderServlet extends BaseServlet {
    private OrderDao orderDao = new OrderDaoImpl();

    /*
     *  查看当前用户的订单信息
     * */
    public void currentUserOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 从session中获取用户session信息
        HttpSession session = req.getSession();
        String user_id = (String) session.getAttribute("user_id");
        // 获取当前用户全部订单信息
        List<Order> current_order = orderDao.getCurrentUserOrder(user_id);
        List<String> book_name = new ArrayList<>();
        for (Order order : current_order) {
            // 通过订单中的book_id 获取book表中的书籍信息
            BookDao bookDao = new BookDaoImpl();
            Book book = bookDao.getBookDetail(order.getBook_id());
            book_name.add(book.getName());
        }
        // 将订单信息传到前端页面
        req.setAttribute("order_list", current_order);
        req.setAttribute("book_name", book_name);
        req.getRequestDispatcher("/order.jsp").forward(req, resp);
    }

    /*
     * 删除用户订单
     * */
    public void deleteCurrentUserOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取订单号
        String order_id = req.getParameter("order_id");
        // 执行删除操作
        orderDao.deleteOrder(order_id);
//        currentUserOrder(req, resp);
        resp.sendRedirect("/order?m=currentUserOrder");
    }

    /*
     * 用户添加订单
     * */
    public void userAddOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取用户和图书信息
        String user_id = req.getParameter("uid");
        String book_id = req.getParameter("book_id");
        int buy_num = Integer.parseInt(req.getParameter("count"));
        float price = Float.parseFloat(req.getParameter("all_price"));
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        // 获取当前时间
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // random 一个订单状态  ['已支付','待发货', '待收货', '已收货']
        List<String> statueList = Arrays.asList("已支付", "待发货", "待收货", "已收货");
        Random rand = new Random();
        String statue = statueList.get(rand.nextInt(statueList.size()));

        // 将订单信息保存到数据库
        Order order = new Order();
        order.setOrder_id(GetOrderIDUtils.getOrderId());
        order.setBook_id(book_id);
        order.setUser_id(user_id);
        order.setBuy_num(buy_num);
        order.setPrice(price);
        order.setStatue(statue);
        order.setCreate_time(sdf.format(date));
        orderDao.save(order);

        if (req.getParameter("cart_id") != null) {
            // 如果是立即购买，则不需要从购物车中删除，否则同时删除购物车里的当前图书
            CartDao cartDao = new CartDaoImpl();
            int cart_id = Integer.parseInt(req.getParameter("cart_id"));
            cartDao.deleteBookFromCart(cart_id);
            resp.sendRedirect("/cart?m=cartList");
        }

        // 给Ajax返回信息
        resp.setContentType("text/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        String str = "{\"msg\":\"购买成功,请在我的订单中查看\",\"status\":true}";
        out.print(str);
        out.flush();
        out.close();
    }
}
